package com.example.afinal;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

public class MyListThread implements Runnable{

    private static final String TAG = "MyListThread";
    Handler handler;

    public void setHandler(Handler handler){
        this.handler = handler;
    }
    @Override
    public void run() {
        Log.i(TAG,"run: ()..................");

        try {
            Thread.sleep(3000);
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }
        List<String> retlist = new ArrayList<String>();
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Elements tables = doc.getElementsByTag("table");
            Element table2 = tables.get(1);
//            Log.i(TAG,"run: table2=" + table2);
            Elements trs = table2.getElementsByTag("tr");
            for (Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                // Log.i(TAG,"run: tds=" + tds);
                if (tds.size()>6) {
                    String rname = tds.get(0).text();
                    String rateStr = tds.get(5).text();
                    Log.i(TAG,"run: " + rname + "==>" + rateStr);
                    retlist.add(rname + "==>" + rateStr);
                }

            }


        } catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }

        //发送数据回主线程
        Message msg = handler.obtainMessage(7,retlist);
        msg.obj = retlist;
        handler.sendMessage(msg);
        Log.i(TAG,"run: msg已发送");
    }
}
